package com.lhsy.djcloud.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.controller.vo.FileMessageVo;
import com.lhsy.djcloud.controller.vo.SearchVo;
import com.lhsy.djcloud.entity.Department;
import com.lhsy.djcloud.entity.FileMessage;
import com.lhsy.djcloud.entity.Upload;
import com.lhsy.djcloud.entity.User;
import com.lhsy.djcloud.entity.dto.UserDto;
import com.lhsy.djcloud.service.DepartmentService;
import com.lhsy.djcloud.service.FileMessageService;
import com.lhsy.djcloud.service.UploadService;
import com.lhsy.djcloud.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangzw
 * @since 2020-09-14
 */
@RestController
@RequestMapping("/fileMessage")
@Api(value = "Server-API",tags = "文件管理")
public class FileMessageController extends BaseController{
    @Autowired private FileMessageService fileMessageService;
    @Autowired private UploadService uploadService;
    @Autowired private UserService userService;
    @Autowired private DepartmentService departmentService;
    /**
     * 获取当前的文件消息列表
     * @param request
     * @return
     */
    @ApiOperation(value = "获取当前用户接收的文件列表")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public ReturnT<List<FileMessage>> getList(HttpServletRequest request,
                                              @RequestBody SearchVo searchVo){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        //根据权限查询当前文件列表的列表
        PageHelper.startPage(searchVo.getPageNo(),searchVo.getPageSize());
        List<FileMessage> fileMessages = fileMessageService.selectByTargetId(currUser.getUserId(),searchVo);
        PageInfo<FileMessage> fileMessagePageInfo = new PageInfo<>(fileMessages);
        fileMessagePageInfo.getList().forEach(fileMessage -> {
            Integer uploadId = fileMessage.getUploadId();
            Upload upload = uploadService.getById(uploadId);
            fileMessage.setSha1(upload.getSha1());
            User user = userService.getById(fileMessage.getSendUserId());
            if (!Objects.isNull(user)){
                Department department = departmentService.getById(user.getDeptId());
                if (Objects.nonNull(department)){
                    fileMessage.setSendDeptName(department.getDeptName());
                }
            }

            User user1 = userService.getById(fileMessage.getTargetUserId());
            if (!Objects.isNull(user1)){
                Department department = departmentService.getById(user1.getDeptId());
                if (Objects.nonNull(department)){
                    fileMessage.setTargetDeptName(department.getDeptName());
                }
            }
        });
        return ReturnT.SUCCESS(fileMessagePageInfo);
    }

    /**
     * 获取当前的文件消息列表
     * @param request
     * @return
     */
    @ApiOperation(value = "获取当前用户发送的文件列表")
    @RequestMapping(value = "/getMyList",method = RequestMethod.POST)
    public ReturnT<List<FileMessage>> getMyList(HttpServletRequest request, @RequestBody SearchVo searchVo){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        //根据权限查询当前文件列表的列表
        PageHelper.startPage(searchVo.getPageNo(),searchVo.getPageSize());
        List<FileMessage> fileMessages = fileMessageService.selectBySendId(currUser.getUserId(),searchVo);
        PageInfo<FileMessage> fileMessagePageInfo = new PageInfo<>(fileMessages);
        fileMessagePageInfo.getList().forEach(fileMessage -> {
            Integer uploadId = fileMessage.getUploadId();
            Upload upload = uploadService.getById(uploadId);
            fileMessage.setSha1(upload.getSha1());
            User user = userService.getById(fileMessage.getSendUserId());
            if (!Objects.isNull(user)){
                Department department = departmentService.getById(user.getDeptId());
                if (Objects.nonNull(department)){
                    fileMessage.setSendDeptName(department.getDeptName());
                }
            }

            User user1 = userService.getById(fileMessage.getTargetUserId());
            if (!Objects.isNull(user1)){
                Department department = departmentService.getById(user1.getDeptId());
                if (Objects.nonNull(department)){
                    fileMessage.setTargetDeptName(department.getDeptName());
                }
            }
        });
        return ReturnT.SUCCESS(fileMessagePageInfo);
    }


    /**
     * 上传文件发送
     * @param fileMessageVo
     * @param request
     * @return
     */
    @ApiOperation(value = "发送文件")
    @RequestMapping(value = "/send",method = RequestMethod.POST)
    public ReturnT send(@RequestBody FileMessageVo fileMessageVo, HttpServletRequest request){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        //查询文件
        Upload upload = uploadService.getBySha1(fileMessageVo.getFileSHA1());
        if(Objects.isNull(upload)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"文件不存在");
        }
        fileMessageVo.getTargetUserIds().forEach(integer -> {
            //添加文件列表
            FileMessage fileMessage = new FileMessage();
            fileMessage.setTenantId(currUser.getTenantId());
            fileMessage.setSendUserId(currUser.getUserId());
            fileMessage.setTargetUserId(integer);
            fileMessage.setTitle(fileMessageVo.getTitle());
            fileMessage.setContent(fileMessageVo.getContent());
            fileMessage.setFileName(upload.getName());
            fileMessage.setFilePath(upload.getPath());
            fileMessage.setUploadId(upload.getId());
            fileMessage.setCreateName(currUser.getUserName());
            fileMessage.setCreateTime(new Date());
            fileMessageService.save(fileMessage);
        });

        return ReturnT.SUCCESS;
    }

    /**
     * 下载文件
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "查看文件详情")
    @RequestMapping(value = "/view/{id}",method = RequestMethod.POST)
    public ReturnT view(@PathVariable Integer id,HttpServletRequest request){
        UserDto currUser = getCurrUser(request);
        //添加文件列表
        FileMessage fileMessage = fileMessageService.getById(id);
        if (Objects.nonNull(fileMessage)){
            if (!fileMessage.getSendUserId().equals(currUser.getUserId())&&!fileMessage.getTargetUserId().equals(currUser.getUserId())){
                return ReturnT.FAIL;
            }
            if (currUser.getUserId().equals(fileMessage.getTargetUserId())){
                fileMessage.setReadFlag(Boolean.TRUE);
                fileMessageService.updateById(fileMessage);
            }

        }
        return ReturnT.SUCCESS(fileMessage);
    }
    /**
     * 查看
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    public ReturnT delete(@PathVariable Integer id, HttpServletRequest request){
        UserDto currUser = getCurrUser(request);
        //添加文件列表
        FileMessage fileMessage = fileMessageService.getById(id);
        if (Objects.nonNull(fileMessage)){
            //todo 当前文件不满足
            /*if (!fileMessage.getSendUserId().equals(currUser.getUserId())){
                return ReturnT.FAIL;
            }*/
            fileMessageService.removeById(fileMessage);
        }
        Upload upload = uploadService.getById(fileMessage.getUploadId());
        if (Objects.isNull(upload)){
            return ReturnT.SUCCESS(fileMessage);
        }
        fileMessage.setSha1(upload.getSha1());
        return ReturnT.SUCCESS(fileMessage);
    }
}

